/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved.
 * secPaver is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package sehandle

import (
	"gitee.com/openeuler/secpaver/engine/selinux/pkg/secontext"
)

func (h *Handle) MatchFileContext(path string, tp secontext.FileClass) *secontext.FileContext {
	for _, fctx := range h.fileContexts {
		if fctx.Match(path, tp) {
			return fctx
		}
	}

	return nil
}

func (h *Handle) GetFileContext(path string, tp secontext.FileClass) *secontext.FileContext {
	for _, fctx := range h.fileContexts {
		if fctx.Path == path {
			return fctx
		}
	}

	return nil
}

// AddFileContext adds a file context to the list
func (h *Handle) AddFileContext(fctx *secontext.FileContext) {
	for i, f := range h.fileContexts {
		if secontext.FileContextCompare(f, fctx) {
			tmp := h.fileContexts[i:]
			h.fileContexts = append(h.fileContexts[:i], fctx)
			h.fileContexts = append(h.fileContexts[:i], tmp...)
		}

	}
}

func (h *Handle) RemoveMaskFileContext(path string) {
	for i, fctx := range h.fileContexts {
		if fctx.Path == path {
			tmp := h.fileContexts[i+1:]
			h.fileContexts = append(h.fileContexts[:i], tmp...)
		}
	}
}
